﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFOpenVideo.Model;
using WPFOpenVideo.Bll;
using System.Windows.Forms;
using System.Threading;
using Timer = System.Windows.Forms.Timer;
using System.IO.Ports;
using System.Text.RegularExpressions;
using MessageBox = System.Windows.Forms.MessageBox;
using System.Windows.Threading;

namespace WPFOpenVideo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        
        //↓************************************公共申明************************************↓//
        private bool IsHide = false;
        private bool StartStop = false;
        private bool IsFull = false;
        private Timer Ti = new Timer();
        private DispatcherTimer Ti2 = new DispatcherTimer();
        private bool IsOpen = false;
        private bool IsOpenForTwoFile = false;
        private Uri StartVideo;
        private Uri ChangeVideo;
        private bool IsChangeOne = false;
        private bool IsStopKey = false;
        private ClassComm com1 = null;
        private TimeSpan media_positon_change;
        private TimeSpan rool_time;
        

        private TaskFactory task_factory;
        private OpretionPortBll New_OpretionPortBll;
        private SetMediaBll New_SetMediaBll;
        //↑************************************公共申明************************************↑//



        public MainWindow()
        {
            InitializeComponent();
            New_OpretionPortBll = new OpretionPortBll() { Media = MediaPlayer1 };
        }


        //↓************************************封装函数************************************↓//



        /// <summary>
        /// 视频播放与暂停
        /// </summary>
       
        private void SetStartStop()
        {

            if (StartStop)
            {
                Start.Visibility = Visibility.Hidden;
                Stop.Visibility = Visibility.Visible;
                MediaPlayer1.Play();
                StartStop = false;
                return;
            }
            else
            {
                Start.Visibility = Visibility.Visible;
                Stop.Visibility = Visibility.Hidden;
                MediaPlayer1.Pause();
                StartStop = true;
                return;
            }
        }

        /// <summary>
        /// 放大缩小图标设置
        /// </summary>
        private void SetFullSmall()
        {
            if (IsFull)
            {
                IsFull = false;
                FullScreen.Visibility = Visibility.Visible;
                SmallScreen.Visibility = Visibility.Hidden;
                return;
            }
            else
            {
                IsFull = true;
                FullScreen.Visibility = Visibility.Hidden;
                SmallScreen.Visibility = Visibility.Visible;
                return;
            }
        }

        /// <summary>
        /// 控件显示
        /// </summary>
        private void SetVisibilityShow()
         {
             if (!IsHide) return;
             Slider2.Visibility = Visibility.Visible;
            this.WindowStyle = WindowStyle.SingleBorderWindow;
            DockPanel1.Visibility = Visibility.Visible;
            IsHide = false;
        }

        /// <summary>
        /// 控件隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetVisibilutyHide(object sender, EventArgs e)
        {
            if (IsHide)
            {
                Ti.Stop();
            }

            Slider2.Visibility = Visibility.Hidden;
            this.WindowStyle = WindowStyle.None;
            DockPanel1.Visibility = Visibility.Hidden;
            IsHide = true;
        }

        /// <summary>
        /// 定时器事件订阅及时间
        /// </summary>
        private void HideShowTimer()
        {
            Ti.Tick += SetVisibilutyHide;
            Ti.Interval = 2000;
        }

        /// <summary>
        /// 文件选择
        /// </summary>
        private void FileSelectBll(out Uri path)
        {

            path = null;
            OpenFileDialog ofd = new OpenFileDialog()
            {
                Filter = "MP4 Files(*.mp4)|*.mp4"
            };
            DialogResult R = ofd.ShowDialog();
            if (R == System.Windows.Forms.DialogResult.OK)
            {
                path= new Uri(ofd.FileName);
                IsChangeOne = true;
            }
        }

        private void LoadLabel3()
        {
            var time_span = MediaPlayer1.NaturalDuration.TimeSpan;
            Label3.Content = string.Format($"/ {time_span}");//为Label3赋值
        }

        private void LoadLabel1()
        {
            string tmp = Regex.Replace(rool_time.ToString(), @"\.\d+$", string.Empty);//正则表达式去除尾部小数位
            Label1.Content = tmp;
        }


        private void Operation(double value_to_timespan)
        {
            media_positon_change = New_SetMediaBll.GetTimeSpan(value_to_timespan);
            MediaPlayer1.Position = media_positon_change;
        }
        //↑************************************封装函数************************************↑//


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Console.WriteLine($"主线程启动，此线程ID为{Thread.CurrentThread.ManagedThreadId}");
            MediaPlayer1.LoadedBehavior = MediaState.Manual;
            HideShowTimer();
            
            New_SetMediaBll = new SetMediaBll();
            task_factory = new TaskFactory();
        }

        private void StopOrStart_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
           this.Dispatcher.InvokeAsync(() => { SetStartStop(); },
                System.Windows.Threading.DispatcherPriority.Normal);
        }

        private void FullScreen_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.Dispatcher.InvokeAsync(() =>
                {
                    if (!IsFull)
                    {
                        this.WindowState = WindowState.Maximized;
                    }
                    else
                    {
                        this.WindowState = WindowState.Normal;
                    }
                },
                System.Windows.Threading.DispatcherPriority.Background);
           
        }

        private void FileSelect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            IsTwoFileSelect();
        }


        private void IsTwoFileSelect()
        {
            if (!IsOpenForTwoFile)
            {
                TwoFileSelect.Visibility = Visibility.Visible;
                IsOpenForTwoFile = true;
            }
            else
            {
                TwoFileSelect.Visibility = Visibility.Hidden;
                IsOpenForTwoFile = false;
            }
        }
        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState==WindowState.Maximized)
            {
                Ti.Start();
            }
            else
            {
                Ti.Stop();
                SetVisibilityShow();
            }
            SetFullSmall();
        }


        private void HiddenArea_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                Ti.Stop();
                SetVisibilityShow();
            }
        }

        private void DockPanel1_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                Ti.Start();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        { 
            New_OpretionPortBll.SendDataThreadFlag = false;
        }

        private void Add1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //if (!IsChangeOne)
            //{
            //    MessageBox.Show("请先选择要切换的视频","警告");
            //    return;
            //}
            FileSelectBll(out StartVideo);
            if (StartVideo == null) return;
                IsTwoFileSelect();
                MediaPlayer1.Source = StartVideo;
                MediaPlayer1.Play();
                Thread.Sleep(500);//线程休眠0.5秒，以便捕捉到视频相关参数信息
                LoadLabel3();

                Slider2.Maximum = MediaPlayer1.NaturalDuration.TimeSpan.TotalMilliseconds;
                Ti2.Tick += (sender1, e1) =>
                {
                    dispatcherTimer_tick();
                    LoadLabel1();
                };
                Ti2.Interval = new TimeSpan(0, 0, 1);
                Ti2.Start();
        }

        private void Add2_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            FileSelectBll(out ChangeVideo);
            New_OpretionPortBll.ChangeVideoBll = ChangeVideo;
        }

        private void Reset_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MediaPlayer1.Stop();
            MediaPlayer1.Source = StartVideo;
            MediaPlayer1.Play();
        }

        private void MediaPlayer1_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaPlayer1.Stop();
            MediaPlayer1.Source = StartVideo;
            MediaPlayer1.Play();
        }


        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                SetStartStop();
                return;
            }

            if (e.Key == Key.Escape && this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
                return;
            }
        }

        private void Setting_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SettingPort.FormSettingPort().ShowDialog(); 
        }

        private void dispatcherTimer_tick()
        {
            Slider2.Value = MediaPlayer1.Position.TotalMilliseconds;
            rool_time= new TimeSpan(0,0,0,0, Convert.ToInt32(Slider2.Value));
        }

        private void Slider2_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MediaPlayer1.Pause();
            Ti2.Stop();
        }

        private void Slider2_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MediaPlayer1.Position = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(Slider2.Value));
            MediaPlayer1.Play();
            Ti2.Start();
        }

        private void Sound_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine($"毫秒时间转换:{new TimeSpan(0,0,0,0,60000)}");
        }
    }
}
